package communication.listeners;

import java.sql.SQLException;
import java.sql.Statement;

import server.Server;
import server.ServerCommunicator;

import message.AuthenticationRequestMessage;
import message.AuthenticationResponseMessage;
import message.Message;
import message.ServerMessageWrapper;
import communication.MessageListener;
import communication.MessageReceivedEvent;

public class AuthenticationListener implements MessageListener
{
	private final ServerCommunicator communicator;
	
	public AuthenticationListener(ServerCommunicator communicator)
	{
		this.communicator = communicator;
	}
	
	private boolean validCrdentials(String username, String password)
	{
		boolean success = false;
		java.sql.Connection dbConnection = Server.getDatabaseConnection();
		
		if (dbConnection != null)
		{
			try
			{
				Statement statement = dbConnection.createStatement();
				
				statement.execute("SELECT COUNT(*) FROM users WHERE username='" + username + "' AND password='" + password + "'");
				
				success = statement.getResultSet().first();
			}
			catch (SQLException ex) { ex.printStackTrace(); }
			
			try
			{
				dbConnection.close();
			}
			catch (SQLException ex) { ex.printStackTrace(); }
		}
		
		return success;
	}
	@Override
	public void messageRecieved(MessageReceivedEvent e)
	{
		ServerMessageWrapper message = ((ServerMessageWrapper) e.getMessage());
		AuthenticationRequestMessage innerMessage = (AuthenticationRequestMessage) message.internalMessage;
		AuthenticationResponseMessage responseMessage = new AuthenticationResponseMessage();
		
		responseMessage.setSuccess(validCrdentials(innerMessage.getUsername(), innerMessage.getPassword()));
		
		communicator.sendMessage(message.connectionId, responseMessage);
	}

	@Override
	public boolean acceptsMessage(Message message)
	{
		if (message.getClass().equals(ServerMessageWrapper.class))
			message = ((ServerMessageWrapper) message).internalMessage;
		
		return message.getClass().equals(AuthenticationRequestMessage.class);
	}

}
